<script setup>
import { onMounted, reactive, ref, computed } from "vue";
import { UserFilled, Lock, Message } from "@element-plus/icons-vue";
import { loginApi, registerApi, verificationApi } from "../../api/LogoIn";
import { ElMessage } from "element-plus";
import router from "../../router";
import { useUserStore, usePermissionStore } from "../../store/index"; // 从统一入口引入
import { userMenuApi } from "../../api/user";
const userStore = useUserStore();
const permissionStore = usePermissionStore();

// 生成一个响应式变量来控制登录或注册的状态
const isLogin = ref(true);
// 切换登录或注册的处理函数
const handleChange = () => {
  isLogin.value = !isLogin.value;
};
// 登录表单数据
const logoForm = reactive({
  userName: "", // 用户名
  passWord: "", //  密码
  validCode: "", // 验证码
});
// 验证码数据
const getValidCode = reactive({
  validCodetext: "获取验证码", // 验证码文本
  time: 60, // 倒计时
  timer: null, // 定时器
});
// 手机号是否有效
const isPhoneValid = computed(() => {
  const phoneReg =
    /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
  return phoneReg.test(logoForm.userName);
});
// 获取验证码函数
const getValidCodeFn = async () => {
  // 如果不是初始状态 或 手机号不合法，则不执行
  if (getValidCode.validCodetext !== "获取验证码" || !isPhoneValid.value)
    return;

  getValidCode.validCodetext = `${getValidCode.time}秒后重新获取`;
  getValidCode.timer = setInterval(() => {
    getValidCode.time--;
    if (getValidCode.time <= 0) {
      clearInterval(getValidCode.timer);
      getValidCode.validCodetext = "获取验证码";
      getValidCode.time = 60;
    } else {
      getValidCode.validCodetext = `${getValidCode.time}秒后重新获取`;
    }
  }, 1000);
  const res = await verificationApi({ tel: logoForm.userName });
  if (res.code == 10000) {
    ElMessage({
      type: "success",
      message: "验证码已发送，请注意查收",
    });
  } else if (code == -1) {
    ElMessage({
      type: "error",
      message: "单个手机号码30秒内发送短信数超过上限",
    });
  }
};
// 登录表单验证规则
const loginRules = {
  userName: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { min: 11, max: 11, message: "长度在 11 个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const phoneReg =
          /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
        if (!phoneReg.test(value)) {
          callback(new Error("请输入正确的手机号"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  passWord: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, max: 16, message: "长度在 4 到 16 个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const passwordReg = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{4,16}$/; // 密码必须包含字母和数字
        if (!passwordReg.test(value)) {
          callback(new Error("密码必须包含字母和数字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  validCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "长度为4位", trigger: "blur" },
  ],
};
// 登录
const loginFormRef = ref(null);
// 提交按钮的状态
const submitting = ref(false);
const login = () => {
  // 如果正在提交，则不执行
  if (!loginFormRef.value || submitting.value) return;
  submitting.value = true;
  // 兜底效验
  loginFormRef.value.validate(async (valid) => {
    try {
      if (valid) {
        // 如果是注册这发送registerApi请求，如果是登录这发送loginApi请求
        if (isLogin.value) {
          // 发送登录请求
          const res = await loginApi(logoForm);
          // token存储在本地
          if (res.code === 10000) {
            getPermissionList();
            // 存储token到store
            userStore.setToken(res.data.token);
            // 存储用户信息
            userStore.setUserInfo(res.data.userInfo);
            localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo));

            // 登录成功
            ElMessage.success("登录成功");
            // 可以在这里处理登录成功后的逻辑，比如跳转到首页
            router.push("/");
          }
        } else {
          // 发送注册请求
          const res = await registerApi(logoForm);
          if (res.code === 10000) {
            // 登录成功
            ElMessage.success("注册成功，请登录");
            // 切换到登录状态
            isLogin.value = true;
          }
        }
        // 重置表单
        logoForm.userName = "";
        logoForm.passWord = "";
        logoForm.validCode = "";
      } else {
        ElMessage.warning("请检查输入");
        return false;
      }
    } finally {
      submitting.value = false;
    }
  });
};
// 获取权限列表
const getPermissionList = async () => {
  const res = await userMenuApi();
  console.log(res);
  // 存储权限列表
  permissionStore.setPermission(res.data);
};
</script>

<template>
  <el-row class="login-container" type="flex" justify="center" align="middle">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img src="../../assets/images/login-head.png" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" underline="never" @click="handleChange">
          {{ !isLogin ? "返回登录" : "注册账号" }}
        </el-link>
      </div>
      <el-form :model="logoForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="userName" required>
          <el-input
            v-model="logoForm.userName"
            placeholder="手机号"
            :prefix-icon="UserFilled"
            autocomplete="new-password"
            clearable
          />
        </el-form-item>
        <el-form-item prop="passWord" required>
          <el-input
            v-model="logoForm.passWord"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            autocomplete="new-password"
            show-password
          />
        </el-form-item>
        <el-form-item prop="validCode" required v-if="!isLogin">
          <el-input
            v-model="logoForm.validCode"
            placeholder="验证码"
            :prefix-icon="Message"
            clearable
          >
            <template #append>
              <span
                @click="getValidCodeFn"
                class="valid_code"
                :class="{
                  disabled:
                    !isPhoneValid ||
                    getValidCode.validCodetext !== '获取验证码',
                }"
              >
                {{ getValidCode.validCodetext }}
              </span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            @click="login(loginFormRef)"
            :disabled="submitting"
          >
            {{ isLogin ? "登录" : "注册" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
.valid_code {
  cursor: pointer;
  &:hover {
    color: #409eff;
  }
}
.disabled {
  color: #aaa;
  cursor: not-allowed;
  &:hover {
    color: #aaa;
  }
}
</style>

